package com.zj.roseoj.judge.codesandbox.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.zj.roseoj.common.ErrorCode;
import com.zj.roseoj.exception.BusinessException;
import com.zj.roseoj.judge.codesandbox.CodeSandbox;
import com.zj.roseoj.judge.codesandbox.model.ExecuteCodeRequest;
import com.zj.roseoj.judge.codesandbox.model.ExecuteCodeResponse;

/**
 * 远程代码沙箱（调用远程接口）
 */
public class RemoteCodeSandbox implements CodeSandbox {

    /**
     * 请求头，用于判断请求用户是否有权限访问
     */
    public static final String AUTH_REQUEST_HEARTH = "auth";

    /**
     * 密钥
     */
    public static final String AUTH_REQUEST_SECRET = "secretKey";

    /**
     * 请求的URL地址
     */
    private static final String URL = "http://localhost:8090/executeCode";

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        String executeCodeRequestStr = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(URL)
                .header(AUTH_REQUEST_HEARTH,AUTH_REQUEST_SECRET)
                .body(executeCodeRequestStr)
                .execute()
                .body();
        if (StrUtil.isNotBlank(responseStr)) {
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR, "executeCode remoteSandBox error, message = " + responseStr);
        }
        return JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);
    }
}
